package org.nanotek.spring.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.nanotek.beans.ArtistCredit;
import org.nanotek.beans.ArtistCreditName;
import org.nanotek.beans.ArtistName;
import org.nanotek.beans.Release;
import org.nanotek.beans.Track;
import org.nanotek.lucene.LuceneUtil;

@SuppressWarnings("serial")
public class ArtistSearchServiceImpl extends ArtistDAOWrapper implements ArtistSearchService {

	private static final transient Logger log = Logger.getLogger(ArtistSearchServiceImpl.class);
	
	@Override
	public List<?> findArtistByName(final  String artistQuery) {
		String tokenizedQuery = tokenizeQuery (artistQuery);
		return findByName(tokenizedQuery , true);
	}

	@Override
	public List<?> findArtistCredit(final  ArtistName searchParameter) {
		List<ArtistCreditName> artistCreditNames = findArtistCreditNameByArtistNameId(searchParameter.getMbid());
		List<ArtistCredit> artistCredits = new ArrayList<ArtistCredit>();
		for (ArtistCreditName artistCreditName : artistCreditNames){ 
			artistCredits.addAll( findCreditsByArtistCreditName(artistCreditName));
		}
		return artistCredits;
	}

	@Override
	public ArtistName findArtistNameById(final String artistIdStr) {
		ArtistName artistName = getArtistNameDAO().findById(new Long(artistIdStr));
		return artistName;
	}
	
	private String tokenizeQuery(final String artistQuery) {
		StringBuilder namePart = new StringBuilder(); 
		List<String> queryPart = LuceneUtil.tokenizeString(new WhitespaceAnalyzer(), artistQuery);
		Iterator<String> queryPartIterator = queryPart.iterator();
		while(queryPartIterator.hasNext()) 
		{ 
			namePart.append(queryPartIterator.next()); 
			if (queryPartIterator.hasNext())
				namePart.append("%");
		}
		log.debug("QueryString Tokenized Artist Query " + namePart.toString());
		return namePart.toString();
	}

	@Override
	public ArtistCredit findArtistCredit(final Long artstCreditId) {
		return getArtistCreditDAO().findById(artstCreditId);
	}
	
	public List<Track> findTrackByArtistCredit (final ArtistCredit artistCredit)
	{ 
		
		return findTrackByArtistCredit(artistCredit);
	}
	
	public List<Release> findReleaseByArtistCredit (final ArtistCredit artistCredit)
	{ 
		
		return findReleaseByArtistCredit(artistCredit);
	}
	
}
